package com.pt.controller;

import com.pt.common.ApiResponse;
import com.pt.entity.Checkin;
import com.pt.entity.User;
import com.pt.service.CheckinService;
import com.pt.service.UserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

@Api(tags = "签到管理")
@RestController
@RequestMapping("/api/checkin")
@RequiredArgsConstructor
public class CheckinController {
    
    private final CheckinService checkinService;
    private final UserService userService;
    
    @ApiOperation("每日签到")
    @PostMapping
    @PreAuthorize("hasRole('USER')")
    public ApiResponse<Map<String, Object>> checkin(HttpServletRequest request) {
        User user = userService.getCurrentUser();
        
        try {
            Checkin checkin = checkinService.checkin(user.getId());
            
            Map<String, Object> result = new HashMap<>();
            result.put("id", checkin.getId());
            result.put("userId", checkin.getUserId());
            result.put("checkinTime", checkin.getCheckinTime());
            result.put("rewardPoints", checkin.getRewardPoints());
            
            return ApiResponse.success(result);
        } catch (RuntimeException e) {
            return ApiResponse.error(e.getMessage());
        }
    }
    
    @ApiOperation("检查今日是否已签到")
    @GetMapping("/status")
    @PreAuthorize("hasRole('USER')")
    public ApiResponse<Map<String, Object>> getCheckinStatus(HttpServletRequest request) {
        User user = userService.getCurrentUser();
        
        boolean hasCheckedIn = checkinService.hasCheckedInToday(user.getId());
        
        Map<String, Object> result = new HashMap<>();
        result.put("hasChecked", hasCheckedIn);
        
        // 如果今天已签到，获取今日奖励
        if (hasCheckedIn) {
            Checkin todayCheckin = checkinService.getTodayCheckin(user.getId());
            if (todayCheckin != null) {
                result.put("todayReward", todayCheckin.getRewardPoints());
            }
        }
        
        return ApiResponse.success(result);
    }
    
    @ApiOperation("获取连续签到天数")
    @GetMapping("/streak")
    @PreAuthorize("hasRole('USER')")
    public ApiResponse<Map<String, Object>> getCheckinStreak(HttpServletRequest request) {
        User user = userService.getCurrentUser();
        
        Integer streak = checkinService.getCheckinStreak(user.getId());
        Integer totalDays = checkinService.getTotalCheckinDays(user.getId());
        
        Map<String, Object> result = new HashMap<>();
        result.put("streak", streak);
        result.put("totalDays", totalDays);
        
        return ApiResponse.success(result);
    }
} 